<template>
  <div class="wrapLimit clx main">
    <div style="padding: 0.2rem">
      <div class="transportCapacityRecord">
        <!-- isCarrier {{isCarrier}} -->
        <el-form ref="inputModel" :rules="rules" :model="inputModel" label-width="120px" class="form-baseinfo">
          <el-row>
            <el-col :span="24">
              <p class="title">下单基本信息</p>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7">
              <el-form-item label="下单人姓名" prop="userName">
                <el-input v-model="inputModel.userName" />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="联系电话" prop="userMobile">
                <el-input v-model="inputModel.userMobile" />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="厂区名称" prop="plantName">
                <el-input v-model="inputModel.plantName" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7">
              <el-form-item label="所属部门" prop="departmentName">
                <el-input v-model="inputModel.departmentName" />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="inputModel.remark" />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="可送货时间" prop="deliverTime">
                <el-date-picker v-model="inputModel.deliverTime" type="date" placeholder="不填默认：不限制时间" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-form
          ref="ordersProducts"
          :rules="rules"
          :inline="true"
          :model="inputModel.ordersProducts"
          label-width="90px"
          class="form-baseinfo"
        >
          <el-row>
            <el-col :span="24">
              <p class="title">产品信息</p>
            </el-col>
          </el-row>
          <el-form-item label="产品类型" prop="categoryNo">
            <el-select
              v-model="inputModel.ordersProducts.categoryNo"
              filterable
              clearable
              style="width: 130px"
              @change="centreTypeChange"
            >
              <el-option v-for="item in centreType" :key="item.id" :value="item.categoryNo" :label="item.cName" />
            </el-select>
          </el-form-item>
          <el-form-item label="物料名称" prop="pNo">
            <el-select v-model="inputModel.ordersProducts.pNo" filterable clearable style="width: 130px">
              <el-option
                v-for="item in smallType"
                :key="item.id"
                :value="item.pNo"
                :label="item.pTitle"
                :disabled="item.plbQuantity == 0 ? true : false"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="购买数量" prop="pCount">
            <el-input v-model="inputModel.ordersProducts.pCount" style="width: 90px" />
          </el-form-item>
          <el-form-item label="员工工号" prop="userJobNum">
            <el-input v-model="inputModel.ordersProducts.userJobNum" style="width: 120px" />
          </el-form-item>
          <el-form-item>
            <el-button size="medium" type="primary" @click="insertData('ordersProducts')">添加</el-button>
          </el-form-item>
          <LPTablePage
            :show-index="true"
            :show-indexfixed="false"
            index-label="序号"
            :table-data="tableData"
            :table-column="tableColumn"
            :total="total"
            :current-page="currentPage"
            :show-page="false"
            align="center"
            @handleSizeChange="handleSizeChange"
            @handleCurrentChange="handleCurrentChange"
          >
            <template slot="couponName" slot-scope="{ row }">
              <div v-for="(item, index) in row.couponName" :key="index">
                <el-link type="primary">{{ item.couponName }}</el-link>
              </div>
            </template>
            <template slot="couponModels" slot-scope="{ row }">
              <div v-if="row.couponModels.length > 0">
                <div v-for="(item, index) in row.couponModels" :key="index">
                  <el-link type="primary" @click="goToCouponManage(item.couponId)">{{ item.couponName }}</el-link>
                </div>
              </div>
            </template>
            <template slot="couponRecordId" slot-scope="{ row }">
              <div v-if="row.couponModels.length > 0">
                <div v-for="(item, index) in row.couponModels" :key="index">
                  <div>{{ item.recordId }}</div>
                </div>
              </div>
            </template>
            <template slot="cz" slot-scope="scope">
              <el-button type="text" @click="deleteInfo(scope.$index)">删除</el-button>
            </template>
          </LPTablePage>
          <el-row style="margin-top: 10px">
            <el-col :span="24">
              <span>汇总：一共{{ tableCount }}件商品，总金额{{ Math.round(totalMoney * 100) / 100 }}元</span>
            </el-col>
          </el-row>
        </el-form>
        <div class="form-baseinfo">
          <el-button size="medium" type="primary" @click="close()">关闭</el-button>
          <el-button size="medium" type="primary" @click="Save('inputModel')">提交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCategoryInfo } from '@/api/LaborProtection/categoryInfo'
import { getProductList } from '@/api/LaborProtection/product'
import { getByIdOrderData, insertAndupdateRemoteOrder, getEmployee, getCouponByUser } from '@/api/LaborProtection/order'
import { closeActiveTag, parseTime } from '@/utils/lpUtils.js'
import LPTablePage from '@/components/LPTablePage/index.vue'

export default {
  name: 'RemoteOrderUpdateOrder',
  components: { LPTablePage },
  data() {
    return {
      id: '',
      inputModel: {
        userName: '',
        userJobNum: '',
        userMobile: '',
        plantName: '',
        departmentName: '',
        jobName: '',
        deliverTime: '',
        remark: '',
        ordersProducts: {
          pNo: '',
          categoryNo: '',
          userName: '',
          userJobNum: '',
          pCount: ''
        }
      },
      data: {},
      tableData: [],
      tableColumn: [
        { label: '物料类型', prop: 'cName' },
        { label: '物料编码', prop: 'pNo' },
        { label: '物料名称', prop: 'pTitle' },
        { label: '单位', prop: 'pUnit', width: 60 },
        { label: '数量', prop: 'pCount', width: 60 },
        { label: '物料销售单价', prop: 'pPrice', width: 120 },
        { label: '下单金额', prop: 'pAmount', width: 80 },
        { label: '优惠券名称', prop: 'couponName', width: 180, render: true },
        { label: '发放记录编号', prop: 'couponRecordId', width: 200, render: true },
        { label: '员工工号', prop: 'userJobNum', width: 120 },
        { label: '员工卡号', prop: 'userCardNo', width: 120 },
        { label: '员工姓名', prop: 'realName' },
        { label: '操作', prop: 'cz', render: true }
      ],
      options: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      PID: 0,
      tableCount: 0,
      totalMoney: 0,
      bigType: [],
      centreType: [],
      smallType: [],
      rules: {
        userName: [{ required: true, message: '请输入下单人姓名', trigger: 'blur' }],
        userMobile: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        plantName: [{ required: true, message: '请输入厂区名称', trigger: 'blur' }],
        departmentName: [{ required: true, message: '请输入所属部门', trigger: 'blur' }],
        pNo: [{ required: true, message: '请选择物料名称', trigger: 'blur' }],
        userJobNum: [{ required: true, message: '请输入员工工号', trigger: 'blur' }],
        pCount: [{ required: true, message: '请输入购买数量', trigger: 'blur' }],
        categoryNo: [{ required: true, message: '请选择物料类型', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.isEditJudge()
    this.getCategoryInfo(2)
  },
  methods: {
    goToCouponManage(id) {
      this.$router.push({
        path: '/laborProtection/couponManage',
        query: {
          data: JSON.stringify({
            id: id,
            back: '/remoteOrder/components/updateOrder'
          })
        }
      })
    },
    isEditJudge() {
      const data = {}
      this.id = this.$route.query.id
      if (this.id != '') {
        getByIdOrderData(this.id).then((res) => {
          if (!res.error) {
            this.inputModel.userName = res.userName
            this.inputModel.userMobile = res.userMobile
            this.inputModel.plantName = res.plantName
            this.inputModel.departmentName = res.departmentName
            this.inputModel.remark = res.remark
            this.inputModel.deliverTime = res.deliverTime
            res.ordersProducts.forEach((item, index) => {
              const data = {}
              data.cName = item.pClassName
              data.pNo = item.pNo
              data.pTitle = item.pTitle
              data.pUnit = item.pUnit
              data.pPrice = Math.round(item.pPrice * 100) / 100
              data.pAmount = Math.round(item.pMoney * 100) / 100
              data.pCount = item.pCount
              data.userCardNo = item.userCardNo
              data.userJobNum = item.userJobNum
              data.realName = item.userName
              this.tableData.push(data)
              this.tableCount = this.tableCount + item.pCount
              this.totalMoney = this.totalMoney + item.pMoney
            })
          }
        })
      }
    },
    /**
     *  1：大类 2：中类 3：小类
     * @param {*} type
     */
    getCategoryInfo(type) {
      const data = {
        CCLass: type,
        SkipCount: 0
      }
      getCategoryInfo(data).then((res) => {
        if (!res.error) {
          this.centreType = res.items
        }
      })
    },
    getProductList(QCategoryNo) {
      const params = {
        PType: 1,
        QCategoryNo: QCategoryNo,
        SkipCount: 0
      }
      getProductList(params).then((res) => {
        this.smallType = res.items
      })
    },
    centreTypeChange() {
      this.inputModel.ordersProducts.pNo = ''
      if (this.inputModel.ordersProducts.categoryNo == '') {
        this.smallType = []
      } else {
        this.getProductList(this.inputModel.ordersProducts.categoryNo)
      }
    },
    handleSearchSubmit() {
      this.currentPage = 1
    },
    handleSearchReset() {
      this.handleSearchSubmit()
    },
    handleSizeChange(v) {
      this.pageSize = v
      this.currentPage = 1
    },
    handleCurrentChange(v) {
      this.currentPage = v
    },
    initialData() {
      this.inputModel.ordersProducts = {
        pNo: '',
        categoryNo: '',
        userName: '',
        userJobNum: '',
        pCount: ''
      }
    },

    insertData(ordersProducts) {
      this.$refs[ordersProducts].validate((valid) => {
        if (valid) {
          const params = {
            JobNum: this.inputModel.ordersProducts.userJobNum
          }
          getEmployee(params).then((res) => {
            console.log(res)
            if (res.realName != null && res.realName != '') {
              const data = {}

              if (this.inputModel.ordersProducts.pCount <= 0) {
                return this.$message.error('购买数量不能小于1')
              }
              const materialList = {}
              this.centreType.forEach((item) => {
                if (item.categoryNo == this.inputModel.ordersProducts.categoryNo) {
                  data.cName = item.cName
                }
              })
              this.smallType.forEach((item) => {
                if (item.pNo == this.inputModel.ordersProducts.pNo) {
                  data.pNo = item.pNo
                  data.pTitle = item.pTitle
                  data.pUnit = item.pUnit
                  data.pPrice = Math.round(item.pPrice * 100) / 100
                  data.pAmount = Math.round(item.pPrice * Number(this.inputModel.ordersProducts.pCount) * 100) / 100
                  data.pCount = Number(this.inputModel.ordersProducts.pCount)
                  materialList.qCategoryNo = item.qCategoryNo
                }
              })
              data.userJobNum = this.inputModel.ordersProducts.userJobNum
              data.userCardNo = res.cardNo
              data.realName = res.realName
              this.totalMoney = this.totalMoney + data.pAmount
              this.tableCount = this.tableCount + data.pCount
              materialList.materialName = data.pTitle
              materialList.materialCode = data.pNo
              materialList.materialCodeNumber = data.pCount
              data.couponName = []
              const data1 = {
                userNo: this.inputModel.ordersProducts.userJobNum,
                material: [{ ...materialList }]
              }
              getCouponByUser(data1).then((res1) => {
                if (res1.mark) {
                  if (res1.orderCouponItemDtos.length > 0) {
                    res1.orderCouponItemDtos.forEach((item) => {
                      data.couponName.push({
                        couponName: item.couponName,
                        id: item.couponRecordId
                      })
                    })
                    console.log(data)
                    this.tableData.push(data)
                    this.initialData()
                  }
                } else {
                  return this.$message.error(res1.topic)
                }
              })
            } else {
              return this.$message.error('员工工号所属无具体人员，请重新输入')
            }
          })
        } else {
          return false
        }
      })
    },
    deleteInfo(index) {
      this.$confirm('是否删除该条产品信息', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      })
        .then(({ value }) => {
          this.$message.success('删除成功')
          this.tableData.splice(index, 1)
          this.tableCount = 0
          this.totalMoney = 0
          this.tableData.forEach((item) => {
            this.tableCount = this.tableCount + item.pCount
            this.totalMoney = this.totalMoney + item.pAmount
          })
        })
        .catch(() => {})
    },
    Save(inputModel) {
      this.$refs[inputModel].validate((valid) => {
        if (valid) {
          if (this.tableData.length == 0) {
            return this.$message.error('产品信息至少为一条')
          }
          const ordersProducts = []
          let soMoney = 0
          this.tableData.forEach((item) => {
            soMoney = soMoney + item.pAmount
            ordersProducts.push({
              pNo: item.pNo,
              pCount: item.pCount,
              userJobNum: item.userJobNum
            })
          })
          const data = {
            SOType: 2, // 1 收银台下单 2 远程下单
            userName: this.inputModel.userName,
            userMobile: this.inputModel.userMobile,
            plantName: this.inputModel.plantName,
            departmentName: this.inputModel.departmentName,
            deliverTime: parseTime(this.inputModel.deliverTime),
            soMoney: soMoney,
            remark: this.inputModel.remark,
            ordersProducts: ordersProducts
          }
          if (this.id != '') {
            data.id = this.id
          }
          if (localStorage.getItem('warehouseType') == null) {
            data.inventoryType = 0
          } else {
            data.inventoryType = 1
          }
          insertAndupdateRemoteOrder(data).then((res) => {
            if (!res.error) {
              this.$message.success('已提交审核')
              this.close()
            }
          })
        } else {
          return false
        }
      })
    },
    close() {
      closeActiveTag(this, '/laborProtection/order/remoteOrder')
    }
  }
}
</script>

<style lang="scss" scoped>
.transportCapacityRecord {
  .btn_area {
    margin-bottom: 0.1rem;
  }

  .form-baseinfo {
    border: 1px solid #dcdfe6;
    padding: 10px;

    .title {
      font-size: 16px;
      font-weight: 600;
    }
  }
}

.main {
  margin: 0.2rem;
}
</style>
